package com.swk.controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.swk.bean.Student;
import com.swk.exception.StudentNotExist;
import com.swk.service.StudentService;

/**
 * 
 * @author 慎伟康
 * 
 * @date 2017年9月21日 下午2:16:05
 * 
 * @Description TODO
 *
 */
@WebServlet("/student")
public class StudentController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public StudentController() {
        super();
    }

	/**
	 * 注销登录
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession(false);
		if(session != null){
			session.removeAttribute("user");
		}
		response.sendRedirect(request.getContextPath() + "/");
	}

	/**
	 * 接口分流
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html");
//		response.setCharacterEncoding("utf-8");
		
		String method = request.getParameter("method");
		if (method != null && method.trim().length() > 0) {
			if("login".equals(method)){
				this.login(request, response);
			}
		}else{
			response.getWriter().write("请求异常！");
		}
		
	}

	/**
	 * 登录接口
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void login(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException{
		String account = request.getParameter("account");
		String password = request.getParameter("password");
		
		if (account == null || account.trim().length() == 0){
			response.getWriter().write("账号不能为空！");
			return;
		}
		if (password == null || password.trim().length() == 0){
			response.getWriter().write("密码不能为空！");
			return;
		}
		
		StudentService ss = new StudentService();
		try {
			Student student = ss.getStudentInfo(account);
			if(!password.equals(student.getPassword())){
				response.getWriter().write("密码错误！");
				return;
			}
			HttpSession session = request.getSession();
			session.setAttribute("user", student);
			response.sendRedirect(request.getContextPath() + "/main.jsp");
		} catch (SQLException e) {
			response.getWriter().write("系统错误！");
		} catch (StudentNotExist e) {
			response.getWriter().write("该用户不存在！");
		}
	}

}
